// 客服相关API配置

// 客服服务配置
const CUSTOMER_SERVICE_CONFIG = {
  // 尝试直接访问后端服务，绕过网关
  baseUrl: 'http://localhost:9216',
  // WebSocket地址
  wsUrl: 'ws://localhost:9216'
}

// 客服API接口
export const customerServiceApi = {
  // 测试接口
  test: () => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${CUSTOMER_SERVICE_CONFIG.baseUrl}/customer-service/test`,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  
  // 创建客服会话
  createSession: () => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${CUSTOMER_SERVICE_CONFIG.baseUrl}/customer-service/session/create`,
        method: 'POST',
        data: {
          userId: 1, // 使用默认用户ID
          userName: '测试用户',
          userAvatar: ''
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  
  // 获取历史消息
  getHistoryMessages: (params) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${CUSTOMER_SERVICE_CONFIG.baseUrl}/customer-service/messages/history`,
        method: 'GET',
        data: {
          sessionId: params.sessionId,
          page: params.page || 1,
          pageSize: params.pageSize || 20
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  
  // 发送消息
  sendMessage: (data) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${CUSTOMER_SERVICE_CONFIG.baseUrl}/customer-service/message/send`,
        method: 'POST',
        data: {
          sessionId: data.sessionId,
          content: data.content,
          messageType: data.type || 'text',
          userId: 1 // 使用默认用户ID
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  
  // 检查在线状态
  checkOnlineStatus: () => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${CUSTOMER_SERVICE_CONFIG.baseUrl}/customer-service/status/online`,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  
  // 上传图片
  uploadImage: (data) => {
    return new Promise((resolve, reject) => {
      uni.request({
        url: `${CUSTOMER_SERVICE_CONFIG.baseUrl}/customer-service/upload/image`,
        method: 'POST',
        data: data,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res.data)
          } else {
            reject(res)
          }
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  
  // 获取AI智能回复
  getAIResponse: async (params) => {
    try {
      // 调用本地AI服务
      const response = await uni.request({
        url: `${CUSTOMER_SERVICE_CONFIG.baseUrl}/customer-service/ai/chat`,
        method: 'POST',
        data: {
          message: params.userMessage,
          sessionId: params.sessionId
        }
      })
      
      if (response.statusCode === 200) {
        return {
          success: true,
          data: {
            reply: response.data.reply || '抱歉，我没有理解您的问题，请重新描述一下。'
          }
        }
      } else {
        throw new Error('AI服务调用失败')
      }
    } catch (error) {
      console.error('调用AI服务失败:', error)
      // 返回默认回复
      return {
        success: false,
        message: 'AI服务暂时不可用，请稍后再试'
      }
    }
  }
}

// 本地智能回复（当第三方API不可用时的备用方案）
export const localAIResponse = {
  // 关键词匹配回复
  getReplyByKeywords: (userMessage) => {
    const message = userMessage.toLowerCase()
    
    // 订单相关
    if (message.includes('订单') || message.includes('下单')) {
      return '您好，关于订单问题，请提供订单号，我会为您查询详细信息。'
    }
    
    // 退款相关
    if (message.includes('退款') || message.includes('退货') || message.includes('换货')) {
      return '您好，关于退款/退货/换货问题，请提供订单号和具体原因，我们会尽快为您处理。'
    }
    
    // 物流相关
    if (message.includes('物流') || message.includes('发货') || message.includes('配送')) {
      return '您好，关于物流配送问题，请提供订单号，我会为您查询最新物流状态。'
    }
    
    // 优惠券相关
    if (message.includes('优惠券') || message.includes('折扣') || message.includes('活动')) {
      return '您好，目前我们有多种优惠活动，您可以在首页-优惠券中心查看并领取适合的优惠券。'
    }
    
    // 商品相关
    if (message.includes('商品') || message.includes('产品') || message.includes('质量')) {
      return '您好，关于商品问题，请提供商品名称和具体问题描述，我会为您详细解答。'
    }
    
    // 账户相关
    if (message.includes('账户') || message.includes('登录') || message.includes('密码')) {
      return '您好，关于账户问题，请提供您的用户名或手机号，我会协助您解决。'
    }
    
    // 默认回复
    const defaultReplies = [
      '您好，我是智能客服助手，很高兴为您服务！请问有什么可以帮助您的？',
      '感谢您的咨询，我会尽力为您提供帮助。请详细描述您的问题。',
      '您好，我是您的专属客服助手，请问有什么需要帮助的吗？',
      '感谢您的耐心等待，我会尽快为您解答问题。'
    ]
    
    return defaultReplies[Math.floor(Math.random() * defaultReplies.length)]
  },
  
  // 智能分析用户意图
  analyzeIntent: (userMessage) => {
    const message = userMessage.toLowerCase()
    
    if (message.includes('?') || message.includes('？')) {
      return 'question'
    } else if (message.includes('谢谢') || message.includes('感谢')) {
      return 'gratitude'
    } else if (message.includes('投诉') || message.includes('不满')) {
      return 'complaint'
    } else if (message.includes('建议') || message.includes('意见')) {
      return 'suggestion'
    } else {
      return 'general'
    }
  }
}

// WebSocket连接管理（用于实时消息推送）
export class CustomerServiceWebSocket {
  constructor(sessionId) {
    this.sessionId = sessionId
    this.ws = null
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
  }
  
  // 连接WebSocket
  connect() {
    try {
      const wsUrl = `ws://localhost:9216/customer-service/ws/${this.sessionId}`
      this.ws = uni.connectSocket({
        url: wsUrl,
        success: () => {
          console.log('WebSocket连接成功')
          this.reconnectAttempts = 0
        }
      })
      
      this.ws.onOpen(() => {
        console.log('WebSocket已打开')
        this.heartbeat()
      })
      
      this.ws.onMessage((res) => {
        this.handleMessage(res.data)
      })
      
      this.ws.onError((error) => {
        console.error('WebSocket错误:', error)
        this.reconnect()
      })
      
      this.ws.onClose(() => {
        console.log('WebSocket已关闭')
        this.reconnect()
      })
    } catch (error) {
      console.error('WebSocket连接失败:', error)
      this.reconnect()
    }
  }
  
  // 发送消息
  send(message) {
    if (this.ws && this.ws.readyState === 1) {
      this.ws.send({
        data: JSON.stringify(message),
        success: () => {
          console.log('消息发送成功')
        },
        fail: (error) => {
          console.error('消息发送失败:', error)
        }
      })
    }
  }
  
  // 处理接收到的消息
  handleMessage(data) {
    try {
      const message = JSON.parse(data)
      // 这里可以触发事件或回调，让页面更新
      uni.$emit('customerServiceMessage', message)
    } catch (error) {
      console.error('解析消息失败:', error)
    }
  }
  
  // 心跳检测
  heartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
    }
    
    this.heartbeatTimer = setInterval(() => {
      this.send({ type: 'heartbeat', timestamp: Date.now() })
    }, 30000) // 30秒发送一次心跳
  }
  
  // 重连
  reconnect() {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      console.log('达到最大重连次数，停止重连')
      return
    }
    
    this.reconnectAttempts++
    console.log(`尝试重连第${this.reconnectAttempts}次`)
    
    setTimeout(() => {
      this.connect()
    }, this.reconnectInterval)
  }
  
  // 关闭连接
  close() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer)
    }
    
    if (this.ws) {
      this.ws.close()
    }
  }
}

// 导出配置
export const CUSTOMER_SERVICE_CONFIG_EXPORT = {
  // 消息类型
  MESSAGE_TYPES: {
    TEXT: 'text',
    IMAGE: 'image',
    FILE: 'file',
    SYSTEM: 'system'
  },
  
  // 消息状态
  MESSAGE_STATUS: {
    SENDING: 'sending',
    SENT: 'sent',
    FAILED: 'failed',
    READ: 'read'
  },
  
  // 客服状态
  SERVICE_STATUS: {
    ONLINE: 'online',
    OFFLINE: 'offline',
    BUSY: 'busy',
    AWAY: 'away'
  }
}
